# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         result_info_service.py
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2022/8/17 08:49
# -------------------------------------------------------------------------------
from abc import ABCMeta, abstractmethod
from functools import wraps

from django.db.models import Sum

from apps.HttpAutoTestService.models import TestcaseResult, ExtMethodResult, SQLResult

__all__ = ['TestcaseResultInfoServiceImpl', 'ExtMethodResultInfoServiceImpl', 'SQLResultInfoServiceImpl']


class ResultInfoService(metaclass=ABCMeta):
    @abstractmethod
    def result_info(self, version):
        """
        获取结果信息
        :param version:
        :return:
        """
        pass


def wrapper_result_info(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # QuerySet
        results = func(*args, **kwargs)
        # 测试结果总数
        result_total = results.count()
        # 测试结果成功数
        result_success = results.filter(status='PASS').count()
        # 测试结果失败数
        result_fail = results.filter(status='FAIL').count()
        # 测试总耗时
        total_elapsed_ms = results.aggregate(total_elapsed_ms=Sum('elapsed_ms'))['total_elapsed_ms'] or 0
        return results, result_total, result_success, result_fail, total_elapsed_ms

    return wrapper


class TestcaseResultInfoServiceImpl(ResultInfoService):

    @wrapper_result_info
    def result_info(self, version):
        return TestcaseResult.objects.filter(version=version, is_deleted=False)


class ExtMethodResultInfoServiceImpl(ResultInfoService):

    @wrapper_result_info
    def result_info(self, version):
        return ExtMethodResult.objects.filter(version=version, is_deleted=False)


class SQLResultInfoServiceImpl(ResultInfoService):

    @wrapper_result_info
    def result_info(self, version):
        return SQLResult.objects.filter(version=version, is_deleted=False)
